const response = require("../utils/response");
const router = require("koa-router")();
const {
    handleDatabaseError,
    dealNotEmpty,
    dealNotEmptyArry,
    paginate,
} = require("../utils/dberrordeal");
const {supplierProduct} = require("../models/supplierProduct");
const Joi = require("joi");
const validationMiddleware = require("../middleware/validate");
router.prefix('/supplier')
const rulesSchema = {
    "/supplier/addProduct": Joi.object({
        name: dealNotEmpty("产品名称"),
        price: dealNotEmptyArry("产品价格"),
        unit: dealNotEmpty("产品单位"),
    }),
    "/supplier/putProduct": Joi.object({
        name: dealNotEmpty("产品名称"),
        price: dealNotEmptyArry("产品价格"),
        unit: dealNotEmpty("产品单位"),
    }),
    "/supplier/delProduct": Joi.object({
        id: dealNotEmpty("产品id"),
    }),

};

router.post("/getProductList", async (ctx, next) => {
    let data = ctx.request.body;
    if (data.isAll) {
        await supplierProduct
            .find()
            .then((res) => {
                response.success(ctx, { data: res });
            })
            .catch((err) => {
                handleDatabaseError(ctx, err);
            });
        return;
    }
    let params = ctx.request.query;
    let query = {};
    if (data.name) query.name = { $regex: data.name, $options: "i" }; // 模糊查询客户名称
    if (data.desc) query.desc = { $regex: data.desc, $options: "i" }; // 模糊查询客户名称
    Object.keys(query).forEach(
        (key) => query[key] === undefined && delete query[key]
    );

    try {
        let dbfres = await paginate(supplierProduct, query, params, []);
        response.success(ctx, {
            data: {
                list: dbfres.results,
                total: dbfres.total,
            },
        });
    } catch (err) {
        handleDatabaseError(ctx, err);
    }
});

router.post(
    "/addProduct",
    validationMiddleware(rulesSchema),
    async (ctx, next) => {
        let data = ctx.request.body;
        await supplierProduct
            .create(data)
            .then(() => {
                response.success(ctx, {});
            })
            .catch((err) => {
                handleDatabaseError(ctx, err, "产品名称已存在");
            });
    }
);

router.post("/getProduct", async (ctx, next) => {
    let id = ctx.request.body.id;
    await supplierProduct
        .findOne({
            _id: id,
        })
        .then((res) => {
            response.success(ctx, { data: res });
        })
        .catch((err) => {
            handleDatabaseError(ctx, err);
        });
});
router.post("/delProduct", async (ctx, next) => {
    let id = ctx.request.body.id;

    await supplierProduct
        .findOneAndDelete({ _id: id })
        .then(() => {
            response.success(ctx, {});
        })
        .catch((err) => {
            handleDatabaseError(ctx, err);
        });
});

router.post(
    "/putProduct",
    validationMiddleware(rulesSchema),
    async (ctx, next) => {
        let data = ctx.request.body;
        await supplierProduct
            .findOneAndUpdate({ _id: data.id }, { $set: data })
            .then(() => {
                response.success(ctx, {});
            })
            .catch((err) => {
                console.log(err);
                handleDatabaseError(ctx, err, "产品名称已存在");
            });
    }
);
module.exports = router;
